package com.ss.web.tagmark.aop;

import javax.persistence.Entity;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import com.ss.web.tagmark.FillOprateInfo;
import com.ss.web.tagmark.FillOprateInfo.Oprate;
import com.ss.web.tagmark.utils.ReflectUtils;

@Component
@Aspect
public class EntityOprateAspect {
	@Pointcut("@annotation(com.ss.web.tagmark.FillOprateInfo)")
	public void annotationMethods() {
	}

	@Around("annotationMethods()")
	public Object around(ProceedingJoinPoint pjp) throws Throwable {
		MethodSignature ms = (MethodSignature) pjp.getSignature();
		FillOprateInfo ann = ms.getMethod().getAnnotation(FillOprateInfo.class);
		if (ann == null) {
			return pjp.proceed();
		}
		Oprate[] os = ann.value();
		if (os == null || os.length < 1) {
			return pjp.proceed();
		}
		Object[] args = pjp.getArgs();
		if (args != null && args.length > 0) {
			try {
				SecurityContextHolder.getContext().getAuthentication().getCredentials();
			} catch (Exception e) {
				e.printStackTrace();
			}
			for (Object arg : args) {
				if (arg == null) {
					continue;
				}
				if (arg.getClass().getAnnotation(Entity.class) == null) {
					continue;// 如果不是Entity，则不处理
				}
				for (Oprate o : os) {
					switch (o) {
					case ADD:
						ReflectUtils.addAddInfo(arg);
						break;
					case MODIFY:
						ReflectUtils.addModifyInfo(arg);
						break;
					}
				}
			}
		}
		return pjp.proceed();
	}

}
